//
//  MainViewController.m
//  gif
//
//  Created by Echo on 13-10-16.
//  Copyright (c) 2013年 Echo. All rights reserved.
//

#import "StudyViewController.h"
#import "PokerControlClient.h"


@interface StudyViewController ()

@end

@implementation StudyViewController
@synthesize time, btnTitle;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        arrayTime = [[NSMutableArray alloc] init];
        arrayBtn = [[NSMutableArray alloc] init];
        [NC addObserver:self selector:@selector(getTempInfo:) name:NOTI_TEMP_INFO object:nil];
    }
    return self;
}
-(void)dealloc{
    [NC removeObserver:self];
}
-(void)getTempInfo:(NSNotification*)noti{
    NSString *codeCmd = noti.object;
    if (codeCmd && m_sheet && pCurBtn) {
        if (pCurBtn.tag < arrayTime.count) {
            DelayInfo *preDelayInfo = [arrayTime objectAtIndex:pCurBtn.tag];
            DelayInfo *delayInfo = [[DelayInfo alloc] init];
            delayInfo.app_cmd = codeCmd;
            delayInfo.time = preDelayInfo.time;
            [arrayTime replaceObjectAtIndex:pCurBtn.tag withObject:delayInfo];
        }
        int i=0;
        for (DelayInfo *info in arrayTime) {
            NSLog(@"index: %d %@ %@", i++, info.app_cmd, info.time);
        }
        for (GoodBtn *btn in arrayBtn) {
            for (int i=0; i<arrayTime.count; i++) {
                if (btn.tag == i) {
                    DelayInfo *delayInfo = [arrayTime objectAtIndex:i];
                    if ([delayInfo.app_cmd length] > 0) {
                        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                        break;
                    }
                }
            }
        }
        
//        DeviceInfo *deviceInfo = [self getDeviceInfo];
//        pDataInfo.isStudy = YES;
//        pDataInfo.app_cmd = codeCmd;
//        if (deviceInfo.type == DEVICE_TV) {
//            [self setBtnState:curBtn];
//        }else if (deviceInfo.type == DEVICE_SOUND) {
//            [self setSoundBtnState:curBtn];
//        }else if (deviceInfo.type == DEVICE_AIR) {
//            [self setAirBtnState:curBtn];
//        }
//        [[DataManager GetInstance] setAllDevices];
        [m_sheet dismissWithClickedButtonIndex:0 animated:YES];
        m_sheet = nil;
    }
}
- (void)btnPressed:(UIButton*)abtn{
    pCurBtn = abtn;
    [[PokerControlClient share] startCmd:@"1" code:nil];
    m_sheet = [[UIAlertView alloc] initWithTitle:@"" message:@"等待学习按键..." delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    [m_sheet show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    m_sheet = nil;
    [[PokerControlClient share] startCmd:@"0" code:nil];
}
-(void)buttonregister{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)ok{
    int count = 0;
    for (int i=0; i<arrayTime.count; i++) {
        DelayInfo *delayInfo = [arrayTime objectAtIndex:i];
        if ([delayInfo.app_cmd length] > 0) {
            count++;
        }
    }
    if ([tf.text length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请输入名称" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        if (count > 5) {
            NSLog(@"确定");
            if (delegate) {
                [delegate studyDelayArray:arrayTime name:tf.text];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
            if ([Global curLanguageEn]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Save failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:STR(@"必须学习完所有按键才能保存") delegate:nil cancelButtonTitle:STR(@"确定") otherButtonTitles:nil, nil];
                [alert show];
            }
        }
    }
}
- (void)viewDidLoad
{
    self.title = STR(@"组合按键学习");
    if ([Global curLanguageEn]) {
        self.title = @"Combine button to learn";
    }
    
    UIBarButtonItem *rightItem = [UIBarButtonItem backImageBarButtonItem:[UIImage imageNamed:@"btn_save.png"] target:self action:@selector(ok)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [super viewDidLoad];
    
    UIImage *image = IMG(@"new_device_bg.png");
    UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-image.size.width/2)/2, 50, image.size.width/2, image.size.height/2)];
    bg.userInteractionEnabled = YES;
    bg.image = image;
    [self.view addSubview:bg];
    
    tf = [[UITextField alloc] initWithFrame:CGRectMake(60, 2, 150, bg.frame.size.height-4)];
    tf.text = @"自定义";
    if (self.btnTitle) {
        tf.text = self.btnTitle;
    }
    tf.returnKeyType = UIReturnKeyDone;
    tf.backgroundColor = [UIColor whiteColor];
    tf.font = [UIFont systemFontOfSize:14];
    [bg addSubview:tf];
    tf.delegate = self;
    
    GoodLabel *descLabel = [GoodLabel labelWithFont:14 title:STR(@"名称：")];
    if (self.btnTitle) {
        descLabel.text = @"Name：";
    }
    descLabel.textColor = [UIColor blackColor];
    descLabel.frame = CGRectMake(15, 0, kScreenWidth, bg.frame.size.height);
    [bg addSubview:descLabel];
    
    for (int i=0; i<6; i++) {
        GoodBtn *btn = [GoodBtn btnWithFont:13];
        [arrayBtn addObject:btn];
        [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i;
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:[NSString stringWithFormat:@"%d", i+1] forState:UIControlStateNormal];
        btn.frame = CGRectMake((SCREEN_WIDTH-492/2)/2, 100+i*40, 492/2-70, 33);
        [btn setBackgroundImage:IMG(@"multi_button_nor.png") forState:UIControlStateNormal];
        [self.view addSubview:btn];
        
        UIImageView *delay = [[UIImageView alloc] initWithImage:IMG(@"conbination_delay_nom.png")];
        delay.userInteractionEnabled = YES;
        delay.frame = CGRectMake(FX(btn)+FW(btn)+15, FY(btn), 118/2, 33);
        [self.view addSubview:delay];
        GoodLabel *label = [GoodLabel labelWithFont:13 title:@""];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"0.5";
        
        DelayInfo *delayInfo = [[DelayInfo alloc] init];
//        delayInfo.app_cmd = @"xxx";
        delayInfo.time = [NSNumber numberWithFloat:0.5];
        [arrayTime addObject:delayInfo];
//        [arrayTime addObject:[NSNumber numberWithFloat:0.5]];
        
        label.frame = CGRectMake(FX(delay)+19, FY(delay), 118/2-19, 33);
        label.tag = 100+i;
        [self.view addSubview:label];
        
        UIButton *btnDelay = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, FW(delay), FH(delay))];
        btnDelay.tag = i;
        [delay addSubview:btnDelay];
        [btnDelay addTarget:self action:@selector(btnDelayPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
}
#pragma -
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)btnDelayPressed:(UIButton*)abtn
{
    self.time = @"0.5";
    curLabel = (GoodLabel *)[self.view viewWithTag:abtn.tag+100];
    
    btnbg = [[UIButton alloc] initWithFrame:self.view.bounds];
    btnbg.backgroundColor = RGB(0, 0, 0, .4);
    [self.navigationController.view addSubview:btnbg];
    
    picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, FH(btnbg)-100, 0, 100)];
    if (IOS7_OR_LATER) {
        picker.backgroundColor = [UIColor grayColor];
    }
    picker.delegate = self;
    picker.dataSource = self;
    picker.showsSelectionIndicator = YES;
    [btnbg addSubview:picker];
    
    CGFloat bgviewY= FY(picker)-44;
    bgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, bgviewY, SCREEN_WIDTH, 44)];
    bgview.userInteractionEnabled = YES;
    bgview.image = [UIImage imageNamed:@"popping_bg.png"];
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 12, SCREEN_WIDTH-50, 19)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = STR(@"请选择间隔时间(单位秒)");
    if ([Global curLanguageEn]) {
        label.text = @"Please select the interval time";
    }
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont boldSystemFontOfSize:14];
    label.backgroundColor = [UIColor clearColor];
    [bgview addSubview:label];
    
    UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(266, 5, 53, 33)];
    [btn setTitle:STR(@"确定") forState:UIControlStateNormal];
    if ([Global curLanguageEn]) {
        [btn setTitle:@"OK" forState:UIControlStateNormal];
    }
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [btn addTarget:self action:@selector(pickStatureDidFinish:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"popping_button.png"] forState:UIControlStateNormal];
    [bgview addSubview:btn];
    
    [btnbg addSubview:bgview];
}
-(void)pickStatureDidFinish:(UIButton*)abtn{
    if (curLabel.tag -100 < arrayTime.count) {
        NSNumber *number = [NSNumber numberWithFloat:[self.time floatValue]];
        DelayInfo *delayInfo = [[DelayInfo alloc] init];
        delayInfo.time = number;
        if (arrayTime.count > curLabel.tag -100) {
            DelayInfo *delayInfo1 = [arrayTime objectAtIndex:curLabel.tag -100];
            delayInfo.app_cmd = delayInfo1.app_cmd;
        }
        [arrayTime replaceObjectAtIndex:curLabel.tag -100 withObject:delayInfo];
    }
    curLabel.text = self.time;
    [btnbg removeFromSuperview]; btnbg = nil;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 6;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

#pragma UIPickerView Delegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (row == 0) {
        return @"0.5";
    }else {
        return [NSString stringWithFormat:@"%d", row];
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (row == 0) {
        self.time = @"0.5";
    }else {
        self.time = [NSString stringWithFormat:@"%d", row];;
    }
}

@end






